<template>
  <!--  公告-->
  <el-divider style="width: 100%"
    ><span style="font-size: 23px; font-family: '楷体'">公告</span></el-divider
  ><br />
  <!--  搜索表单-->
  <el-form :inline="true" :model="searchNotice">
    <el-form-item label="公告标题">
      <el-input
        style="width: 200px"
        v-model="searchNotice.noticeTitle"
        type="text"
        autocomplete="off"
        placeholder="输入搜索标题"
        clearable
      />
    </el-form-item>
    <el-form-item label="公告类型">
      <el-select v-model="searchNotice.noticeType" placeholder="选择公告类型" clearable>
        <el-option v-for="item in noticeTypeList" :label="item.value" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="公告状态">
      <el-select v-model="searchNotice.noticeState" placeholder="选择公告状态" clearable>
        <el-option v-for="item in noticeStateList" :label="item.value" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">搜索</el-button>
      <el-button type="info" @click="resetForm">清空</el-button>
      <span style="margin-left: 50px">
        <el-button type="success" style="width: 100px" @click="insertNotice">+ 新 增</el-button>
      </span>
    </el-form-item>
  </el-form>

  <br />

  <!--  新增公告对话框-->
  <el-dialog v-model="dialogInsertVisible" center align-center :title="dialogTitle" width="45%">
    <el-form v-model="notice" ref="noticeRuleFormRef" :rules="noticeInfoRules" :model="notice">
      <el-form-item label="公告标题" prop="noticeTitle">
        <el-input
          maxlength="15"
          v-model="notice.noticeTitle"
          placeholder="请输入公告标题"
          clearable
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="公告类型" prop="noticeType">
        <el-input
          v-model="notice.noticeType"
          placeholder="请输入公告类型"
          clearable
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="公告内容" prop="noticeContent">
        <el-input
          resize="none"
          rows="7"
          show-word-limit
          maxlength="200"
          type="textarea"
          v-model="notice.noticeContent"
          placeholder="请输入公告内容"
          clearable
        />
      </el-form-item>
      <span style="font-size: 13px">公告文件和公告内容是二选一，或者两个都选</span>
      <el-form-item label="公告文件">
        <el-upload
          v-if="
            fileList[0].name != '' &&
            fileList[0].name != null &&
            fileList[0].url != '' &&
            fileList[0].url != null
          "
          v-model:file-list="fileList"
          action="/api/admin/upload"
          :headers="token"
          :on-success="handleSucces"
          :on-preview="handlePreview"
          :before-remove="beforeRemove"
          :limit="1"
          :on-exceed="handleExceed"
        >
          <template #trigger>
            <el-button type="primary">上传文件</el-button>
          </template>
          <template #tip>
            <div style="width: 400px"></div>
          </template>
        </el-upload>

        <el-upload
          v-else
          action="/api/admin/upload"
          :headers="token"
          :on-success="handleSucces"
          :on-preview="handlePreview"
          :before-remove="beforeRemove"
          :limit="1"
          :on-exceed="handleExceed"
        >
          <template #trigger>
            <el-button type="primary">上传文件</el-button>
          </template>
          <template #tip>
            <div style="width: 400px"></div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogInsertVisible = false">关闭</el-button>
        <el-button type="primary" @click="saveNotice(noticeRuleFormRef)">
          {{ dialogButton }}
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!--  公告列表-->
  <el-table :data="noticeInfo" show-overflow-tooltip border>
    <el-table-column type="index" label="序号" width="60" align="center" />
    <el-table-column property="noticeTitle" label="公告标题" width="230" align="center" />
    <el-table-column property="noticeContent" label="公告内容" align="center" />
    <el-table-column label="公告相关文件" align="center">
      <template v-slot="row">
        <span v-if="row.row.noticeFileName === '' || row.row.noticeFileName === null">无</span>
        <el-link @click="openNew(row.row.noticeFileUrl)">{{ row.row.noticeFileName }}</el-link>
      </template>
    </el-table-column>
    <el-table-column property="noticeType" label="公告类型" width="120" align="center" />
    <el-table-column property="noticeState" label="公告状态" width="90" align="center" />
    <el-table-column property="createTime" label="发布日期" width="180" sortable align="center" />
    <el-table-column property="updateTime" label="更新日期" width="180" sortable align="center" />
    <el-table-column label="操作" width="240" align="center">
      <template v-slot="row">
        <el-button
          v-if="row.row.noticeState == '已隐藏'"
          type="success"
          @click="updateNoticeState(row.row.noticeId, '使用中')"
          >使用</el-button
        >
        <el-button v-else type="warning" @click="updateNoticeState(row.row.noticeId, '已隐藏')"
          >隐藏</el-button
        >
        <el-button type="primary" @click="updateNotice(row.row.noticeId)">编辑</el-button>
        <el-button type="danger" @click="sureDelete(row.row.noticeId)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!--  分页-->
  <div style="margin-top: 10px">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      background
      @size-change="SizeChange"
      @current-change="CurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, reactive } from 'vue'
import {
  ElMessage,
  ElMessageBox,
  ElTable,
  FormInstance,
  FormRules,
  UploadFile,
  UploadFiles,
  UploadProps,
  UploadUserFile
} from 'element-plus'
import {
  deleteNoticeById,
  getAllNotice,
  getNoticeById,
  getNoticeInfo,
  insert,
  update,
  updateState
} from '@/apis/notice'
import { getToken } from '@/utils/token'

const openNew = (url: string) => {
  window.open(url)
}
// 用于搜索和分页
const searchNotice = ref({
  noticeTitle: '',
  noticeType: '',
  noticeState: ''
})
const pageSize = ref(5)
const currentPage = ref(1)
const total = ref(30)
const dialogInsertVisible = ref(false)
const token = ref({ token: getToken() })
const dialogTitle = ref()
const dialogButton = ref()

interface Notice {
  noticeId: number
  noticeTitle: string
  noticeContent: string
  noticeFileName: string
  noticeFileUrl: string
  noticeType: string
  noticeState: string
  createTime: string
  updateTime: string
}

const noticeInfo = ref<Notice[]>([
  {
    noticeId: 1,
    noticeTitle: '测试公告1',
    noticeContent: '测试1',
    noticeFileName: 'element-plus-logo.svg',
    noticeType: '156',
    noticeState: '使用中',
    noticeFileUrl: 'https://element-plus.org/images/element-plus-logo.svg',
    createTime: '2023-11-23 17:32:15',
    updateTime: '2023-11-23 17:32:15'
  }
])

const notice = ref<Notice>({
  noticeId: 1,
  noticeTitle: '',
  noticeContent: '',
  noticeFileName: '',
  noticeFileUrl: '',
  noticeType: '',
  noticeState: '使用中',
  createTime: '',
  updateTime: ''
})
const noticeStateList = ref([
  {
    value: '使用中'
  },
  {
    value: '已隐藏'
  }
])
const noticeTypeList = ref([{ value: '' }])
const fileList = ref<UploadUserFile[]>([
  {
    name: '',
    url: ''
  }
])
const noticeRuleFormRef = ref<FormInstance>()
const noticeInfoRules = reactive<FormRules<typeof notice>>({
  noticeTitle: [{ required: true, message: '请填写公告标题', trigger: 'burl' }],
  noticeType: [{ required: true, message: '请填写公告类型', trigger: 'burl' }],
  noticeContent: [{ required: true, message: '请选填写公告内容', trigger: 'burl' }]
})
const page = () => {
  getNoticeInfo(
    searchNotice.value.noticeTitle,
    searchNotice.value.noticeType,
    searchNotice.value.noticeState,
    pageSize.value,
    currentPage.value
  ).then((res) => {
    console.log('获取公告信息')
    if (res.data.code === 1) {
      console.log('获取成功')
      noticeInfo.value = res.data.data.rows
      total.value = res.data.data.total
    } else {
      ElMessage({ type: 'error', message: res.data.msg })
      console.log('获取失败')
    }
  })
}

onMounted(() => {
  getAllNotice('').then((res) => {
    if (res.data.code === 1) {
      let type = ref(new Set())
      for (let i = 0; i < res.data.data.length; i++) {
        type.value.add(res.data.data[i].noticeType)
      }
      let i = 0
      for (let v of type.value.values()) {
        noticeTypeList.value[i] = { value: v }
        i++
      }
    } else {
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
  page()
})

const updateNoticeState = (noticeId: number, noticeState: string) => {
  updateState(noticeId, noticeState).then((res) => {
    if (res.data.code === 1) {
      if (noticeState === '使用中') {
        ElMessage({ type: 'success', message: '公告开启使用' })
      }
      if (noticeState === '已隐藏') {
        ElMessage({ type: 'warning', message: '公告已隐藏' })
      }
      page()
    } else {
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
}

const insertNotice = () => {
  notice.value = {}
  fileList.value = [{ name: '', url: '' }]
  dialogTitle.value = '新增公告'
  dialogButton.value = '添加'
  dialogInsertVisible.value = true
}

const submitForm = () => {
  currentPage.value = 1
  page()
}
const resetForm = () => {
  searchNotice.value = {
    noticeTitle: '',
    noticeType: '',
    noticeState: ''
  }
  page()
}
const SizeChange = (val: number) => {
  pageSize.value = val
  page()
}
const CurrentChange = (val: number) => {
  currentPage.value = val
  page()
}
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  window.open(uploadFile.url)
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(`文件数量不超过 1 个`)
}

const handleSucces: UploadProps['onSuccess'] = (
  response: any,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  notice.value.noticeFileName = response.data.name
  notice.value.noticeFileUrl = response.data.url
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(`是否移除文件 ${uploadFile.name} ?`).then(
    () => {
      fileList.value = [{ name: '', url: '' }]
      notice.value.noticeFileUrl = ''
      notice.value.noticeFileName = ''
    },
    () => false
  )
}

const sureDelete = (noticeId: number) => {
  ElMessageBox.confirm('确认删除该公告吗?', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteNoticeById(noticeId).then((res) => {
        if (res.data.code === 1) {
          ElMessage({ type: 'success', message: '删除成功' })
          page()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '取消删除' })
    })
}
const updateNotice = (noticeId: number) => {
  dialogTitle.value = '编辑公告'
  dialogButton.value = '保存'
  dialogInsertVisible.value = true
  getNoticeById(noticeId).then((res) => {
    if (res.data.code === 1) {
      notice.value = res.data.data
      fileList.value[0].name = res.data.data.noticeFileName
      fileList.value[0].url = res.data.data.noticeFileUrl
    } else {
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
}

const saveNotice = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (notice.value.noticeId != '' && notice.value.noticeId != null) {
        // 编辑
        update(notice.value).then((res) => {
          if (res.data.code === 1) {
            ElMessage({ type: 'success', message: '修改成功' })
            dialogInsertVisible.value = false
            page()
            notice.value = {}
          } else ElMessage({ type: 'error', message: res.data.msg })
        })
      } else {
        //插入
        insert(notice.value).then((res) => {
          if (res.data.code === 1) {
            ElMessage({ type: 'success', message: '插入成功' })
            dialogInsertVisible.value = false
            fileList.value = [{ name: '', url: '' }]
            page()
            notice.value = {}
          } else ElMessage({ type: 'error', message: res.data.msg })
        })
      }
    } else return false
  })
}
</script>
<style scoped></style>
